<template>
  <n-space vertical>
    <n-form
      ref="formRef"
      inline
      :model="formValue"
      label-placement="left"
      :rules="rules"
    >
      <n-form-item label="页面名" class="input" path="name">
        <n-input v-model:value="formValue.name" />
      </n-form-item>
      <n-form-item label="页面路径" class="input" path="path">
        <n-input v-model:value="formValue.path" />
      </n-form-item>
      <n-form-item label="页面状态" class="input" path="status">
        <n-select v-model:value="formValue.status" :options="statusOptions" />
      </n-form-item>
      <n-form-item label="页面排序" class="input" path="order">
        <n-input-number v-model:value="formValue.order" />
      </n-form-item>
      <n-form-item label="开启评论" class="input" path="isCommentOpen">
        <n-switch v-model:value="formValue.isCommentOpen" />
      </n-form-item>
      <n-form-item>
        <n-button @click="createFunc"> 保存 </n-button>
      </n-form-item>
    </n-form>
    <Markdown
      class="markdown"
      v-model:text="formValue.content"
      v-model:htmlText="formValue.contentHtml"
    />
  </n-space>
</template>

<script setup lang="ts">
import {
  NSpace,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NInputNumber,
  NSwitch,
  type FormInst,
} from "naive-ui";
import {
  StatusContent,
  statusOptions,
  type createPage,
  create as apiPageCreate,
  updateOne as apiPageUpdate,
  findOneById as apiPageFindOneById,
} from "~/api/page";
useHead({
  title: "页面编辑", //网站标题
});
definePageMeta({
  title: "页面编辑",
});
const route = useRoute();
const { id } = route.query;
const formValue = ref<createPage>({
  name: "",
  path: "",
  status: StatusContent.Draft,
  order: 0,
  isCommentOpen: true,
  content: "",
  contentHtml: "",
});
const rules = {
  name: {
    pattern: /^.{2,10}$/,
    message: "页面名长度大于2小于10",
    trigger: "blur",
  },
  path: {
    pattern: /^.{2,10}$/,
    message: "路径长度大于2小于10",
    trigger: "blur",
  },
};

const formRef = ref<FormInst | null>(null);
const createFunc = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (errors) naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    if (!formValue.value.content) naiveui.message.error("内容不能为空");
    if (id !== null && id !== undefined) {
      await apiPageUpdate(id as string, formValue.value);
    } else {
      await apiPageCreate(formValue.value);
    }
  });
};
const findPage = async () => {
  if (!id) return;
  const res = await apiPageFindOneById(id as string);
  if (res.code === 0) {
    formValue.value = res.data;
  }
};
onMounted(async () => {
  findPage();
});
</script>
<style lang="scss" scoped>
.input {
  flex: 1;
}
.markdown {
  height: 80vh;
}
</style>
